package com.xujie.chat.client.handler;

import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import com.xujie.chat.message.NettyConstant;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Xujie
 * @since 2024/12/28 22:19
 **/


public class AuthReqHandler extends ChannelInboundHandlerAdapter {
	private final Logger LOG = LoggerFactory.getLogger(AuthReqHandler.class);


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		/*发出认证请求*/
		MyMessage loginMsg = buildLoginReq();
		LOG.info("请求服务器认证 : " + loginMsg);
		ctx.writeAndFlush(loginMsg);
	}

	private MyMessage buildLoginReq() {
		MyMessage message = new MyMessage();
		MsgHeader msgHeader = new MsgHeader();
		msgHeader.setType(MessageType.LOGIN_REQ.value());
		message.setMyHeader(msgHeader);
		return message;
	}

	public void channelRead(ChannelHandlerContext ctx, Object msg)
					throws Exception {

		MyMessage message = (MyMessage) msg;
		/*是不是握手成功的应答*/
		if (message.getMyHeader() != null
						&& message.getMyHeader().getType() == MessageType.LOGIN_RESP.value()) {
			LOG.info("通过认证，移除本处理器，进入业务通信 : {}", message.getBody());
			ctx.channel().attr(NettyConstant.CHANNEL_ID_KEY).set(message.getBody().toString());
			ctx.pipeline().remove(this);
			ReferenceCountUtil.release(msg);
		} else {
			ctx.fireChannelRead(msg);
		}
	}
}
